<template>
  <div class="flink-mappings">
    <!-- 添加/编辑映射对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加作业映射' : '编辑作业映射'"
      width="700px"
    >
      <el-form
        ref="formRef"
        :model="mappingForm"
        :rules="formRules"
        label-width="120px"
      >
        <el-form-item label="模块名称" prop="module_name">
          <el-input v-model="mappingForm.module_name" placeholder="请输入模块名称" />
        </el-form-item>
        <el-form-item label="作业名称" prop="job_name">
          <el-input v-model="mappingForm.job_name" placeholder="请输入作业名称" />
        </el-form-item>
        <el-form-item label="入口类" prop="entry_class">
          <el-input v-model="mappingForm.entry_class" placeholder="请输入入口类" />
        </el-form-item>
        <el-form-item label="JAR包名称" prop="jar_name">
          <el-input v-model="mappingForm.jar_name" placeholder="请输入JAR包名称" />
        </el-form-item>
        <el-form-item label="JAR包路径" prop="jar_path">
          <el-input v-model="mappingForm.jar_path" placeholder="请输入JAR包路径" />
        </el-form-item>
        <el-form-item label="默认并行度" prop="default_parallelism">
          <el-input-number
            v-model="mappingForm.default_parallelism"
            :min="1"
            :max="32"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="默认启动参数" prop="default_program_args">
          <el-input
            v-model="mappingForm.default_program_args"
            type="textarea"
            :rows="3"
            placeholder="请输入默认启动参数"
          />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="mappingForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入描述"
          />
        </el-form-item>
        <el-form-item label="状态" prop="is_active">
          <el-switch v-model="mappingForm.is_active" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <el-card>
      <template #header>
        <div class="card-header">
          <span>作业映射管理</span>
          <div class="header-actions">
            <el-button type="primary" size="small" @click="showAddDialog">添加映射</el-button>
            <el-button type="success" size="small" @click="handleBatchImport">批量导入</el-button>
            <el-button size="small" @click="loadMappings">刷新</el-button>
          </div>
        </div>
      </template>
      
      <el-table :data="mappings" style="width: 100%" v-loading="loading">
        <el-table-column prop="module_name" label="模块名称" />
        <el-table-column prop="job_name" label="作业名称" />
        <el-table-column prop="entry_class" label="入口类" show-overflow-tooltip />
        <el-table-column prop="jar_name" label="JAR包" show-overflow-tooltip />
        <el-table-column prop="default_parallelism" label="默认并行度" width="100" />
        <el-table-column prop="is_active" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.is_active ? 'success' : 'danger'" size="small">
              {{ row.is_active ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button type="text" size="small" @click="editMapping(row)">
              编辑
            </el-button>
            <el-button type="text" size="small" @click="toggleMapping(row)">
              {{ row.is_active ? '禁用' : '启用' }}
            </el-button>
            <el-button type="text" size="small" @click="deleteMapping(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { flinkApi } from '@/api/flink'
import type { FlinkJobMapping } from '@/types'

const mappings = ref<FlinkJobMapping[]>([])
const loading = ref(false)
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const formRef = ref<FormInstance>()

// 表单数据
const mappingForm = ref<Partial<FlinkJobMapping>>({
  module_name: '',
  job_name: '',
  entry_class: '',
  jar_name: '',
  jar_path: '',
  default_parallelism: 1,
  default_program_args: '',
  description: '',
  is_active: true
})

// 表单验证规则
const formRules: FormRules = {
  module_name: [
    { required: true, message: '请输入模块名称', trigger: 'blur' }
  ],
  job_name: [
    { required: true, message: '请输入作业名称', trigger: 'blur' }
  ],
  entry_class: [
    { required: true, message: '请输入入口类', trigger: 'blur' }
  ],
  jar_name: [
    { required: true, message: '请输入JAR包名称', trigger: 'blur' }
  ],
  jar_path: [
    { required: true, message: '请输入JAR包路径', trigger: 'blur' }
  ]
}

const loadMappings = async () => {
  loading.value = true
  try {
    const response = await flinkApi.getJobMappings()
    mappings.value = response.data.items
  } catch (error) {
    console.error('Failed to load mappings:', error)
    ElMessage.error('加载映射列表失败')
  } finally {
    loading.value = false
  }
}

const showAddDialog = () => {
  dialogType.value = 'add'
  mappingForm.value = {
    module_name: '',
    job_name: '',
    entry_class: '',
    jar_name: '',
    jar_path: '',
    default_parallelism: 1,
    default_program_args: '',
    description: '',
    is_active: true
  }
  dialogVisible.value = true
}

const editMapping = (mapping: FlinkJobMapping) => {
  dialogType.value = 'edit'
  mappingForm.value = { ...mapping }
  dialogVisible.value = true
}

const submitForm = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    if (dialogType.value === 'add') {
      await flinkApi.createJobMapping(mappingForm.value)
      ElMessage.success('添加成功')
    } else {
      await flinkApi.updateJobMapping(mappingForm.value.id!, mappingForm.value)
      ElMessage.success('更新成功')
    }
    
    dialogVisible.value = false
    loadMappings()
  } catch (error) {
    console.error('Form submission failed:', error)
    ElMessage.error('操作失败')
  }
}

const toggleMapping = async (mapping: FlinkJobMapping) => {
  try {
    await flinkApi.toggleJobMapping(mapping.id, !mapping.is_active)
    ElMessage.success(mapping.is_active ? '禁用成功' : '启用成功')
    loadMappings()
  } catch (error) {
    console.error('Toggle mapping failed:', error)
    ElMessage.error('操作失败')
  }
}

const deleteMapping = async (mapping: FlinkJobMapping) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除映射 "${mapping.job_name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await flinkApi.deleteJobMapping(mapping.id)
    ElMessage.success('删除成功')
    loadMappings()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Delete failed:', error)
      ElMessage.error('删除失败')
    }
  }
}

const handleBatchImport = () => {
  ElMessage.info('批量导入功能开发中...')
}

onMounted(() => {
  loadMappings()
})
</script>

<style scoped>
.flink-mappings {
  padding: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 